import numpy as np
import matplotlib.pyplot as plt

# 设置中文显示
plt.rcParams["font.family"] = ["WenQuanYi Micro Hei"]
plt.rcParams["axes.unicode_minus"] = False  # 正确显示负号

# 给定的数据点
wx2 = [44.90, 44.89, 44.89, 45.07, 45.35, 46.08, 46.83, 47.81, 48.31]
wy2 = [-33.86, -32.94, -31.97, -31.17, -30.9, -30.54, -30.3, -30.14, -30.1]

# 将列表转换为numpy数组以便进行多项式拟合
x = np.array(wx2)
y = np.array(wy2)

# 进行多项式拟合
# 三次多项式拟合 (degree=3)
cubic_coeffs = np.polyfit(x, y, 3)
cubic_poly = np.poly1d(cubic_coeffs)

# 五次多项式拟合 (degree=5)
quintic_coeffs = np.polyfit(x, y, 5)
quintic_poly = np.poly1d(quintic_coeffs)

# 生成用于绘制拟合曲线的x值（更密集的点）
x_fit = np.linspace(min(x), max(x), 1000)

# 计算拟合曲线上的y值
y_cubic_fit = cubic_poly(x_fit)
y_quintic_fit = quintic_poly(x_fit)

# 创建图形
plt.figure(figsize=(10, 6))

# 绘制原始数据点
plt.scatter(x, y, color='black', s=50, label='原始数据点')

# 绘制三次多项式拟合曲线
plt.plot(x_fit, y_cubic_fit, color='blue', linewidth=2, 
         label=f'三次多项式拟合: $y = {cubic_poly.coeffs[0]:.4f}x^3 + {cubic_poly.coeffs[1]:.4f}x^2 + {cubic_poly.coeffs[2]:.4f}x + {cubic_poly.coeffs[3]:.4f}$')

# 绘制五次多项式拟合曲线
plt.plot(x_fit, y_quintic_fit, color='red', linewidth=2, linestyle='--',
         label=f'五次多项式拟合: $y = {quintic_poly.coeffs[0]:.4f}x^5 + {quintic_poly.coeffs[1]:.4f}x^4 + {quintic_poly.coeffs[2]:.4f}x^3 + {quintic_poly.coeffs[3]:.4f}x^2 + {quintic_poly.coeffs[4]:.4f}x + {quintic_poly.coeffs[5]:.4f}$')

# 添加标题和标签
plt.title('三次多项式与五次多项式拟合对比', fontsize=15)
plt.xlabel('x坐标', fontsize=12)
plt.ylabel('y坐标', fontsize=12)

# 添加网格和图例
plt.grid(True, linestyle='--', alpha=0.7)
plt.legend(fontsize=10)

# 调整布局并显示
plt.tight_layout()
plt.show()

# 打印拟合多项式的系数
print("三次多项式系数 (从x^3到常数项):", cubic_coeffs)
print("五次多项式系数 (从x^5到常数项):", quintic_coeffs)
    